package org.yaukie.auth.service.impl;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.yaukie.auth.constant.AjaxResult;
import org.yaukie.auth.constant.AuthCons.Login;
import org.yaukie.auth.entity.LoginBody;
import org.yaukie.auth.entity.LoginUser;
import org.yaukie.auth.service.api.LoginHandlerService;
import org.yaukie.base.exception.UserDefinedException;
import org.yaukie.base.redis.RedisOrMapCache;
import org.yaukie.base.system.ASyncFactory;
import org.yaukie.base.system.ASyncManager;
import org.yaukie.base.util.DateUtils;
import org.yaukie.base.util.MessageTools;
import org.yaukie.base.util.SpringContextUtil;
import org.yaukie.base.util.StringTools;

@Component
public class LoginHandlerServiceImpl implements LoginHandlerService {
    private static final Logger log = LoggerFactory.getLogger(LoginHandlerServiceImpl.class);
    @Autowired
    private TokenHandlerServiceImpl tokenHandlerService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisOrMapCache redisCache;
    @Autowired
    private ASyncManager aSyncManager;

    public LoginHandlerServiceImpl() {
    }

    public String login(LoginBody loginBody) {
        String uuid = loginBody.getUuid();
        String capchaCodeKey = "captcha_codes:" + uuid;
        String code = loginBody.getVerifyCode();
        String codeOfRedis = this.redisCache.getCacheObject(capchaCodeKey) + "";
        if (StringTools.isEmpty(codeOfRedis)) {
            this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginBody.getUserName(), Login.LOGIN_FAIL.getDes(), MessageTools.message("yaukie.user.jcaptcha.expire", new Object[0]), new Object[0]));
            throw new UserDefinedException(MessageTools.message("yaukie.user.jcaptcha.expire", new Object[0]));
        } else {
            this.redisCache.deleteObject(capchaCodeKey);
            if (!code.equals(codeOfRedis)) {
                this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginBody.getUserName(), Login.LOGIN_FAIL.getDes(), MessageTools.message("yaukie.user.jcaptcha.error", new Object[0]), new Object[0]));
                throw new UserDefinedException(MessageTools.message("yaukie.user.jcaptcha.error", new Object[0]));
            } else {
                Authentication authentication = null;
                String jwtToken = null;

                try {
                    authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginBody.getUserName(), loginBody.getPassWord()));
                    LoginUser loginUser = (LoginUser)authentication.getPrincipal();
                    jwtToken = this.tokenHandlerService.buildToken(loginUser);
                    SpringContextUtil.getRequest().getSession().setAttribute("currentUserName", loginUser.getXUser().getUserName());
                    SpringContextUtil.getRequest().getSession().setAttribute("currentDeptName", "SmartKettle-演示部门");
                    this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginBody.getUserName(), Login.LOGIN_SUCCESS.getDes(), MessageTools.message("yaukie.user.login.success", new Object[0]), new Object[0]));
                    log.info("登录成功,会话将会在{}后过期", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date(loginUser.getExpireTime())));
                    return jwtToken;
                } catch (Exception var10) {
                    if (var10 instanceof BadCredentialsException) {
                        this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginBody.getUserName(), Login.LOGIN_FAIL.getDes(), MessageTools.message("yaukie.user.password.not.match", new Object[0]), new Object[0]));
                        throw new UserDefinedException(MessageTools.message("yaukie.user.password.not.match", new Object[0]));
                    } else {
                        StringWriter stringWriter = new StringWriter();
                        var10.printStackTrace(new PrintWriter(stringWriter));
                        this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginBody.getUserName(), Login.LOGIN_FAIL.getDes(), stringWriter.toString().substring(0, 253), new Object[0]));
                        throw new UserDefinedException(var10.getMessage());
                    }
                }
            }
        }
    }

    public AjaxResult logout(String token) {
        LoginUser loginUser = this.tokenHandlerService.getLoginUser(SpringContextUtil.getRequest());

        try {
            this.tokenHandlerService.delLoginUser(token);
        } catch (Exception var4) {
            this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginUser.getUsername(), Login.LOGIN_OUT_FAIL.getDes(), var4.getMessage(), new Object[0]));
            throw new UserDefinedException("LOGIN_MODULE", Login.LOGIN_OUT_FAIL.getDes());
        }

        this.aSyncManager.execute(ASyncFactory.recordLoginInfo(loginUser.getUsername(), Login.LOGIN_OUT.getDes(), MessageTools.message("yaukie.user.logout.ok", new Object[0]), new Object[0]));
        return AjaxResult.success(Login.LOGIN_OUT.getDes());
    }
}
